<?php
namespace app\zhongcan\controller;

use app\zhongcan\model\NewsModel;
use cmf\controller\AdminBaseController;

class NewsController extends AdminBaseController
{
    public function index()
    {
        $title= input('title');
        $author= input('author');
        $where= [];
        if($title){
            $where[] = ['title','like',"%$title%"];
        }
        if($author){
            $where[] = ['author','like',"%$author%"];
        }
        $data = NewsModel::order('list_order','desc')
            ->where($where)
            ->paginate('10');
        return $this->fetch('index',[
            'data' => $data
        ]);
    }

    public function add()
    {

        return $this->fetch('add');
    }

    public function addPost()
    {
        $data = input();
        $save = NewsModel::create($data);
        if($save){
             $this->success('添加成功');
        }else{
             $this->error('添加失败');
        }
    }
    public function edit()
    {
        $id=input('id');
        $data = NewsModel::find($id);
        return $this->fetch('edit',[
            'data' => $data
        ]);
    }

    public function editPost()
    {
        $data = input();
        $save = NewsModel::update($data);
        if($save){
            $this->success('修改成功');
        }else{
            $this->error('修改失败');
        }
    }
    public function delete()
    {
        $id=input('id');
        $delete = NewsModel::destroy($id);
        if($delete){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }
    public function list_order()
    {
        $model= new NewsModel();
        parent::listOrders($model);
        $this->success('排序成功');
    }


    public function detail()
    {
        $id=input('id/d');
        $news=NewsModel::find($id);
        $content = $news['content'];
        $content1 = htmlspecialchars_decode($content);
        $content2 = cmf_replace_content_file_url($content1, true);
        $news['content'] = $content2;
        $this->assign('news',$news);
        return $this->fetch('detail');
    }

    public function switch()
    {
        $id = input('param.id', 0);
        $new = NewsModel::find($id);
        if ($new) {
            // 切换状态
            $new->switch = $new->switch == 1 ? 0 : 1;

            if ($new->save()) {
                $this->success('状态切换成功', 'News/index');
            } else {
                $this->error('状态切换失败', 'News/index');
            }
        } else {
            $this->error('新闻不存在', 'News/index');
        }
    }
}
